package router

import (
	"monthly-test4/handler"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func Init() *gin.Engine {
	r := gin.Default()

	r.Use(Cors())

	r.Static("/static", "./static")

	r.POST("/login", handler.Login)          //用户登录
	r.GET("/userList", handler.UserList)     //用户列表
	r.GET("/userSelect", handler.UserSelect) //用户搜索

	r.POST("/userRoleAdd", handler.UserRoleAdd)  //用户角色添加
	r.GET("/userRoleList", handler.UserRoleList) //用户角色列表

	r.POST("/roleNodeAdd", handler.RoleNodeAdd)  //角色权限添加
	r.GET("/roleNodeList", handler.RoleNodeList) //角色权限列表

	r.POST("/carAdd", handler.CarAdd) //汽车添加

	r.POST("/orderAdd", handler.OrderAdd) //订单添加

	r.GET("/carOrderList", handler.CarOrderList)     //汽车订单列表
	r.GET("/carOrderSelect", handler.CarOrderSelect) //汽车订单详情
	return r
}
